<?php
/**
 * @author   Fung Wing Kit <wengee@gmail.com>
 * @version  2018-11-02 16:57:26 +0800
 */
namespace fwkit\LaravelWechat;

class Manager
{
    protected $defaultKey = 'default';

    protected $clients = [];

    protected $accounts = [];

    private static $classes = [
        'minapp' => Minapp\Client::class,
        'mp' => Mp\Client::class,
        'work' => Work\Client::class,
    ];

    public function __construct()
    {
        $wechatCfg = config('wechat');
        $this->defaultKey = array_pull($wechatCfg, 'default', 'default');
        $this->accounts = (array) array_pull($wechatCfg, 'accounts', []);
    }

    public function addAccount(string $key, array $config)
    {
        $this->accounts[$key] = $config;
        return $this;
    }

    public function client(?string $key = null)
    {
        $key = $key ?? $this->defaultKey;
        if (!isset($this->clients[$key])) {
            $client = $this->_loadClient($key);
            $this->clients[$key] = $client;
            return $client;
        }

        return $this->clients[$key];
    }

    protected function _loadClient(string $key)
    {
        $config = $this->accounts[$key] ?? null;
        if (empty($config)) {
            return null;
        }

        $accountType = array_pull($config, 'type', 'minapp');
        $className = self::$classes[$accountType] ?? null;
        return $className ? new $className($config) : null;
    }

    public function __call(string $name, array $arguments)
    {
        $client = $this->client();
        if (method_exists($client, $name)) {
            return call_user_func_array([$client, $name], $arguments);
        }

        throw new \Exception(sprintf(
            'The required method "%s" does not exist for %s.',
            $name,
            get_class($client)
        ));
    }
}
